<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 检测人员管理
 */
namespace app\index\service;

use app\common\model\ImageModel;
use app\common\model\OperateModel;
use app\common\model\ProtectModel;
use app\common\model\TemplateModel;
use think\Exception;
use think\Db;
class TemplateService
{
    protected static $templateModel;
    protected static $protectModel;
    protected static $imageModel;

    /**
     * zws
     * TemplateService constructor.
     * @param TemplateModel $templateModel
     * @param ProtectModel $protectModel
     * @param ImageModel $imageModel
     */
    public function __construct(TemplateModel $templateModel, ProtectModel $protectModel,
                                ImageModel $imageModel)
    {
        self::$templateModel = $templateModel;
        self::$protectModel = $protectModel;
        self::$imageModel = $imageModel;
    }

    /**
     * zws
     * 获取模板列表
     * @param $request
     * @return array
     */
    public function template_list($request)
    {
        if(empty($request->page))
        {
            $request->page = 1;
        }
        if(empty($request->limit))
        {
            $request->limit = 20;
        }
        $type = $request->role;
        $where = [];
        if($type == 2)
        {
            $where['user_id'] = $request->tokenId;
        }
        $count = self::$templateModel->where($where)->count();
        if ($count < 1) {
            return ['links' => [], 'count' => $count];
        }
        if($request->page > 0)
        {
            $result = self::$templateModel->where($where)
                ->page($request->page, $request->limit)
                ->order('create_time', 'desc')
                ->select();
        }else
        {
            $result = self::$templateModel->where($where)
                ->order('create_time', 'desc')
                ->select();
        }
        $result->map(function (&$item){
            $item->imgs;
            return $item;
        });
        if($result)
        {
            $path = config('param_config.imagePath');
            $filePath = config('app.app_host').substr($path, 1);
            foreach ($result as $k=>$v)
            {
                $result[$k]->start_date = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
                $result[$k]->end_date = $v['update_time'] ? date('Y-m-d H:i:s', $v['update_time']) : '';
                $result[$k]->res_limit = 0;
                if($type == 1)
                {
                    $result[$k]->res_limit = 1;
                }else
                {
                    if($type == 2 && $request->tokenId == $v['user_id'])
                    {
                        $result[$k]->res_limit = 1;
                    }
                }
                if($v['imgs'])
                {
                    foreach ($v['imgs'] as $k1=>$v1)
                    {
                        $v['imgs'][$k1]->path = $v1['path'];
                        $v['imgs'][$k1]->img_url = $v1['img_url'] ? $filePath.$v1['img_url'] : '';
                        $v['imgs'][$k1]->date = $v1['create_time'] ? date('Y-m-d H:i:s', $v1['create_time']) : '';
                    }
                }
            }
        }
        return ['links' => $result, 'count' => $count];
    }

    /**
     * zws
     * 删除模板
     * @param $request
     * @return array
     */
    public function del_template($request)
    {
        if(empty($request->template_id))
        {
            app_fail(8594);
        }
        $template_data = self::$templateModel->where('id', '=', $request->template_id)->find();
        if(empty($template_data))
        {
            app_fail(8593);
        }
//        if(($request->role != 2 || $request->tokenId != $template_data->user_id) && $request->role
//            != 1)
//        {
//            app_fail(9985);
//        }
        try{
            $result = self::$templateModel->where(['id'=>$request->template_id])->delete();
            return $result;
        }catch (Exception $e){
            app_fail(9899);//编辑失败
        }
    }

    /**
     * 上传保护的模板
     * @param $params
     * @return array
     */
    public function add_template($params)
    {
        if(empty($params))
        {
            app_fail(9997);
        }
        if(!isset($params['res_code']) || !$params['res_code'])
        {
            app_fail(8599);
        }
        $res_data = self::$protectModel->where(['res_code'=>$params['res_code']])->find();
        if(!$res_data)
        {
            app_fail(8595);
        }
        if(!isset($params['template_name']) || !$params['template_name'])
        {
            app_fail(8588);
        }
        $data = array(
            'res_code'=>$params['res_code'],
            'user_id'=>$params['tokenId'],
            'template_name'=>$params['template_name'],
            'remark'=>isset($params['remark']) ? $params['remark'] : '',
            'template_proto'=>isset($params['template_proto']) ? $params['template_proto'] : '',
            'create_time'=>time(),
            'update_time'=>time(),
        );

        Db::startTrans();
        try{
            $operateModel = new OperateModel();
            $operate_data = $operateModel->where(['res_code'=>$params['res_code'],
                    'user_id'=>$params['tokenId']])->find();
            if(!$operate_data)
            {
                $add_operate_data = [
                    'res_code' => $params['res_code'],
                    'user_id' => $params['tokenId'],
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                $operateModel->save($add_operate_data);
            }
            self::$templateModel->save($data);
            Db::commit();
            return ['template_id'=>self::$templateModel->id];
        }catch (Exception $e){
            Db::rollback();
            app_fail(9899);//编辑失败
        }
    }

    /**
     * zws
     * 上传模板图片
     * @param $params
     * @return bool|void
     *
     */
    public function add_template_img($params)
    {
        if(empty($params))
        {
            app_fail(9997);
        }
        if(!isset($params['template_id']) || !$params['template_id'])
        {
            app_fail(8594);
        }
        $template_data = self::$templateModel->where(['id'=>$params['template_id']])->find();
        if(!$template_data)
        {
            return app_fail(8593);
        }
        if(!isset($params['image']) || !$params['image'])
        {
            return app_fail(9979);
        }
        $imagePath = config('param_config.imagePath');
        try {
            // 添加报告图片流
            if (count($params['image']) > 0) {
                $data = [];
                foreach ($params['image'] as $key => $file) {
                    $info = $file->validate(['size' => 4096000, 'ext' => 'jpg,png,gif,jpeg'])->move($imagePath);
                    if ($info) {
                        $data[] = [
                            'template_id' => $params['template_id'],
                            'img_url' => $info->getSaveName(),
                            'user_id' => $params['tokenId'],
                            'path' => $_FILES['image']['name'][$key], //TODO 图片本地路径待完善
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                    }
                }
                self::$imageModel->saveAll($data);
            }
            return true;
        } catch (\Exception $e) {
            app_fail(9996);
        }
    }
}